<?php

/**
 * Caching class
 */
class MyCache {

    /**
     * Cache lifetime in days
     * 
     * @var integer
     */
    private static $lifetime = 7;

    /**
     * Read value from Cache
     * 
     * @param  string $key
     * @return string
     */
    public static function read($key) {
        $value = false;

        list($filename, $base) = self::parseKey($key);
        $path = self::getPath() . DS . implode(DS, array($base, $filename));

        $mtime = (int)@filemtime($path);
        if (is_file($path) && !self::isExpired($mtime)) {
            $value = file_get_contents($path);
        }
        
        return $value;
    }

    /**
     * Store value in Cache
     * @param  string $key
     * @param  mixed  $value
     * 
     * @return long          (bytes written)
     */
    public static function write($key, $value) {
        list($filename, $base) = self::parseKey($key);
        $path = self::getPath() . DS . implode(DS, array($base, $filename));

        self::makeDir($base);
        return file_put_contents($path, $value);
    }

    public static function emptyDir($dir) {
        $path = self::getPath() . DS . $dir;
        if ($dir = opendir($path)) {
            while ($f = readdir($dir)) {
                if (!in_array($f, array(".", ".."))) {
                    unlink($path . DS . $f);
                }
            }
        }
    }

    /**
     * Get Cache base path
     * 
     * @return string
     */
    private static function getPath() {
        $root = dirname(dirname(__FILE__));
        return implode(DS, array($root, "tmp", "cache", "images"));
    }

    /**
     * Parse key/path, separate basePath from filename
     * 
     * @param  string $key
     * @return array       (filename, basePath)
     */
    private static function parseKey($key) {
        $items = preg_split('/[\/\\\\]/', $key);
        
        $filename = array_pop($items);
        $path     = implode(DS, $items);

        return array($filename, $path);
    }

    /**
     * Create Cache directory/basePath
     * 
     * @param  string $path (relative to Cache's basePath)
     */
    private static function makeDir($path) {
        $path = self::getPath() . DS . $path;
        if (! is_dir($path)) {
            mkdir($path, 0777, true);
        }
    }

    /**
     * Verify if given timestamp is expired
     * @param  int  $time
     * @return boolean
     */
    private static function isExpired($time) {
        $now      = time();
        $lifetime = self::$lifetime * DAY;

        return $time>0 && ($now - $lifetime)>$time;
    }

}

?>